package com.csun.nusing.ui.activity;

import android.Manifest;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.csun.nusing.R;
import com.csun.nusing.bean.UrlBean;
import com.csun.nusing.bean.jsonbean.BaseJsonBean;
import com.csun.nusing.bean.jsonbean.FilePostJsonBean;
import com.csun.nusing.presenter.UserInfoPresenter;
import com.csun.nusing.presenter.inter.IBase;
import com.csun.nusing.ui.BaseActivity;
import com.csun.nusing.ui.myview.RoundImageView;
import com.csun.nusing.ui.myview.SelectPicPopupWindow;
import com.csun.nusing.util.IntentUtils;
import com.csun.nusing.util.PhotoUtils;
import com.csun.nusing.util.SPUtils;
import com.csun.nusing.util.TakePictureManager;
import com.csun.nusing.util.ToastUtil;
import com.google.gson.Gson;
import com.home.administrator.okhttplibrary.IOkTaskCallback;
import com.home.administrator.okhttplibrary.OkHttpTask;
import com.home.administrator.okhttplibrary.OkHttpTask.OkHttpTaskBuidler.OkType;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 用户信息界面 ClassName: UserInfoActivity
 * 
 * @Description: TODO
 * @author fzq
 * @date 2017-10-27
 */
public class UserInfoActivity extends BaseActivity<UserInfoPresenter> implements
		IBase {

	protected static final int REQUESTCODE_TAKE = 0x1;
	private static final int REQUESTCODE_PICK = 0x2;
	private static final int REQUESTCODE_CUTTING = 0x3;
	protected static final String IMAGE_FILE_NAME = "temphead.jpg";
	private RoundImageView headiv;
	private RelativeLayout sexrl;
	private RelativeLayout repsdrl;
	private SelectPicPopupWindow menuWindow;
	private String urlpath;
	private EditText nameet;
	private TextView sextv;
	private String username;
	private String usersex="0";
	private String userPic;
	private ImageView baocuniv;
	private PopupWindow mPopupWindow;
	private RadioGroup popsexrg;
	private String userid;
	private String authorization;
	protected FilePostJsonBean bean;
	private String userPicId;
	private View popview;
	private static final int CODE_GALLERY_REQUEST = 0xa0;
	private static final int CODE_CAMERA_REQUEST = 0xa1;
	private static final int CODE_RESULT_REQUEST = 0xa2;
	private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
	private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
	private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
	private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
	private Uri cropImageUri;
	private boolean photoFlag;//拍照状态符
	private TakePictureManager takePictureManager;
	private Uri imageUri;

	@Override
	public int getContentViewId() {
		return R.layout.activity_nursing_userinfo;
	}

	@Override
	public void initSubViews(View view) {
		// TODO Auto-generated method stub
		super.initSubViews(view);
		findView();
		initSexPop();
	}

	/**
	 * 初始话控件
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-27
	 */
	private void findView() {
		baocuniv = findViewById(R.id.userinfo_baocun_iv);
		headiv = findViewById(R.id.nursing_userinfo_head_iv);
		sexrl = findViewById(R.id.nursing_userinfo_sex_tv);
		repsdrl = findViewById(R.id.nursing_userinfo_repsd_tv);
		nameet = findViewById(R.id.userinfo_name_et);
		sextv = findViewById(R.id.userinfo_sex_tv);
		headiv.setOnClickListener(new click());
		sexrl.setOnClickListener(new click());
		repsdrl.setOnClickListener(new click());
		baocuniv.setOnClickListener(new click());
	}

	@Override
	public void initData() {
		super.initData();
		username = getIntent().getStringExtra("username");
		usersex = getIntent().getStringExtra("usersex");
		userPic = getIntent().getStringExtra("userPic");
		userid = getIntent().getStringExtra("userid");
		userPicId = getIntent().getStringExtra("userPicId");
		if (username != null && !username.equals("null")) {
			nameet.setText("" + username);
		}else{
			nameet.setHint("请填写姓名");
		}
		if (userPic.length()>5) {
			Glide.with(this).load(userPic).into(headiv);
		}
		if (usersex.equals("0")) {
			sextv.setText("男");
		} else {
			sextv.setText("女");
		}
	}

	private void initSexPop() {
		View popupView = getLayoutInflater().inflate(
				R.layout.layout_popupwindow, null);
		mPopupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, true);
		mPopupWindow.setTouchable(true);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(),
				(Bitmap) null));
		popview = popupView.findViewById(R.id.layout_popwindow_view);
		popview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mPopupWindow.dismiss();
			}
		});
		popsexrg = popupView
				.findViewById(R.id.nursing_pop_sex_select_rg);
		popsexrg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.nursing_pop_sex_select_one_rb:
					usersex = "0";
					sextv.setText("男");
					break;
				case R.id.nursing_pop_sex_select_two_rb:
					usersex = "1";
					sextv.setText("女");
					break;
				}
			}
		});
	}

	/**
	 * 点击事件 ClassName: click
	 * 
	 * @Description: TODO
	 * @author fzq
	 * @date 2017-11-1
	 */
	private class click implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.nursing_userinfo_head_iv:
				choosePic();
				break;
			case R.id.nursing_userinfo_sex_tv:
				chooseSex(v);
				break;
			case R.id.nursing_userinfo_repsd_tv:
				IntentUtils.startActivity(UserInfoActivity.this,
						NursingRepsdActivity.class);
				break;
			case R.id.userinfo_baocun_iv:
				saveInfo();
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 保存修改
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-11-2
	 */
	public void saveInfo() {
		authorization = (String) SPUtils.get(this, "authorization", "");
		Map<String, String> param = new HashMap<String, String>();
		param.put("userid", userid);
		param.put("realname", "" + nameet.getText().toString().trim());
		param.put("sex", usersex);
		param.put("headpicid", userPicId);
		OkHttpTask.newInstance(this).post(param, OkType.form)
				.addHeader("authorization", authorization)
				.enqueue(new IOkTaskCallback() {
					@Override
					public void onSuccess(String result) {
						if (result != null) {
							Log.e("FZQ", "---" + result);
							Gson gson = new Gson();
							BaseJsonBean baseJsonBean = gson.fromJson(result,
									BaseJsonBean.class);
							if (baseJsonBean.isStatus()) {
								ToastUtil.showMessage(getApplicationContext(),
										baseJsonBean.getMessage());
								back();
							}
						}
					}
				}).start(UrlBean.UPUSERINFOURL);
	}

	protected void back() {
		Intent intent = new Intent();
		intent.putExtra("userPicPath", userPic);
		username = nameet.getText().toString().trim();
		intent.putExtra("usersex", usersex);
		intent.putExtra("username", username);
		setResult(0x55, intent);
		finish();
	}

	/**
	 * 选择性别
	 * 
	 * @param v
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-11-2
	 */
	public void chooseSex(View v) {
		if (usersex.equals("0")) {
			popsexrg.check(R.id.nursing_pop_sex_select_one_rb);
		} else {
			popsexrg.check(R.id.nursing_pop_sex_select_two_rb);
		}
		mPopupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
	}

	/**
	 * 拍照上传 相册选择
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-11-1
	 */
	public void choosePic() {
		menuWindow = new SelectPicPopupWindow(this, itemsOnClick);
		menuWindow.showAtLocation(findViewById(R.id.nursing_userinfo_head_iv),
				Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
	}

	private OnClickListener itemsOnClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			menuWindow.dismiss();
			switch (v.getId()) {
				case R.id.takePhotoBtn:
					autoObtainCameraPermission();
					break;
				case R.id.pickPhotoBtn:
					autoObtainStoragePermission();
					break;
			default:
				break;
			}
		}
	};

	/**
	 * 自动获取相机权限
	 */
	private void autoObtainCameraPermission() {

		if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
				|| ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

			if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
				Log.e("fzq", "您已经拒绝过一次");
			}
			ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
		} else {//有权限直接调用系统相机拍照
			if (hasSdcard()) {
				imageUri = Uri.fromFile(fileUri);
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
					imageUri = FileProvider.getUriForFile(UserInfoActivity.this, "com.csun.nusing.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
				PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
			} else {
				Log.e("fzq", "设备没有SD卡！");
			}
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);

		switch (requestCode) {
			case CAMERA_PERMISSIONS_REQUEST_CODE: {//调用系统相机申请拍照权限回调
				if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					if (hasSdcard()) {
						imageUri = Uri.fromFile(fileUri);
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
							imageUri = FileProvider.getUriForFile(UserInfoActivity.this, "com.csun.nusing.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
						PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
					} else {
						Log.e("fzq", "设备没有SD卡！");
					}
				} else {
					Log.e("fzq", "请允许打开相机！！");
				}
				break;


			}
			case STORAGE_PERMISSIONS_REQUEST_CODE://调用系统相册申请Sdcard权限回调
				if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
				} else {

					Log.e("fzq",  "请允许打操作SDCard！！");
				}
				break;
		}
	}

	private int output_X = 480;
	private int output_Y = 480;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case CODE_CAMERA_REQUEST://拍照完成回调
					cropImageUri = Uri.fromFile(fileCropUri);
					PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
					break;
				case CODE_GALLERY_REQUEST://访问相册完成回调
					if (hasSdcard()) {
						cropImageUri = Uri.fromFile(fileCropUri);
						Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
							newUri = FileProvider.getUriForFile(this, "com.csun.nusing.fileprovider", new File(newUri.getPath()));
						PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
					} else {
						Log.e("fzq", "设备没有SD卡！");
					}
					break;
				case CODE_RESULT_REQUEST:
					Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
					urlpath = cropImageUri.getPath();
					Log.e("fzq","------"+urlpath);
					postphoto(urlpath);
					if (bitmap != null) {
						showImages(bitmap);
					}
					break;
			}
		}
	}


	/**
	 * 自动获取sdk权限
	 */

	private void autoObtainStoragePermission() {
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
			ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
		} else {
			PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
		}

	}

	private void showImages(Bitmap bitmap) {
		headiv.setImageBitmap(bitmap);
	}

	/**
	 * 检查设备是否存在SDCard的工具方法
	 */
	public static boolean hasSdcard() {
		String state = Environment.getExternalStorageState();
		return state.equals(Environment.MEDIA_MOUNTED);
	}
	/**
	 * 上传图片
	 * 
	 * @Description: TODO
	 * @param @param filePath
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-11-1
	 */
	private void postphoto(String filePath) {
		File file = new File(filePath);
		authorization = (String) SPUtils.get(this, "authorization", "");
		MultipartBody.Builder requestBody = new MultipartBody.Builder()
				.setType(MultipartBody.FORM);
		RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
		String filename = file.getName();
		requestBody.addFormDataPart("file", filename, body);
		requestBody.addFormDataPart("fileDesc", "头像");
		
		Request request = new Request.Builder()
				.addHeader("authorization", authorization)
				.url(UrlBean.FILEPOSTURL).post(requestBody.build()).tag(this)
				.build();
		OkHttpTask.newinstance(this).newBuilder()
				.readTimeout(20000, TimeUnit.MILLISECONDS).build()
				.newCall(request).enqueue(new Callback() {
					@Override
					public void onFailure(Call call, IOException e) {
						Log.i("fzq", "onFailure");
						ToastUtil.showMessage(getApplicationContext(), "上传失败");
					}

					@Override
					public void onResponse(Call call, Response response)
							throws IOException {
						if (response.isSuccessful()) {
							Gson gson = new Gson();
							bean = gson.fromJson(response.body().string(),
									FilePostJsonBean.class);
							if (bean.getData() != null
									&& bean.getData().size() != 0) {
								runOnUiThread(new Runnable() {

									@Override
									public void run() {
										userPicId = ""
												+ bean.getData().get(0)
														.getResourceid();
										userPic = ""
												+ bean.getData().get(0)
														.getResourcepath();
										ToastUtil.showMessage(
												getApplicationContext(),
												bean.getMessage());
									}
								});
							}
						}
					}
				});
	}

}
